package com.auth.config.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * 自定义客户端认证。服务器对客户端进行验证，验证没有问题返回凭证
 */
@Component
public class BaseClientDetailService implements ClientDetailsService {

    private static final Logger log = LoggerFactory.getLogger(BaseClientDetailService.class);

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        log.info("接收到clientId：{}", clientId);
        BaseClientDetails client = null;
        // 真实开发从数据库进行查询client，scope 对应权限集
        // TODO: 2018/12/19

        //以下是测试使用
        if ("client".equals(clientId)) {
            client = new BaseClientDetails();
            client.setClientId(clientId);
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            client.setClientSecret(passwordEncoder.encode("123456"));
            //client.setResourceIds(Arrays.asList("order"));
            client.setAuthorizedGrantTypes(Arrays.asList("authorization_code",
                    "client_credentials", "refresh_token", "password", "implicit"));// 该client允许的授权类型
            //不同的client可以通过 一个scope 对应 权限集
           client.setScope(Arrays.asList("all"));
            client.setAuthorities(AuthorityUtils.createAuthorityList("admin_role"));
            client.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(1)); //1天
            client.setRefreshTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(1)); //1天


        }
        // 不存在该client
        if (client == null) {
            throw new NoSuchClientException("No client width requested id: " + clientId);
        }
        log.info("客户端认证结束：{}", client.toString());
        return client;
    }

}
